<?php
/**
 *         
 * #######################################################################
 *           +----------------------------------------------+
 *           | THIS FILE IS A PART OF "PHP ZONES" FRAMEWORK | 
 *           +----------------------------------------------+
 *           
 *  	THIS CODE IS PROTECTED UNDER Apache Software License
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 * 	Simply stating :
 * 		Proprietary Software linking: Yes
 * 		Distribution of this software : Yes
 * 		Redistributing of the code with changes: You can
 * 		Compatible with GNU GPL : NO :D
 *
 * 	Feel free to change and use but don't need to share the code 
 * though that will be very much appreciated.
 *
 * 	www.phpzones.com, or mail: mailtoaman@gmail.com
 * #######################################################################
 */

/**
 * Sanitizes an input
 * @param $input the inp
 * @param $link
 */
function zSanitize($input){

	if(is_array($input)){

		foreach($input as $k=>$i){
			$output[$k]=zSanitize($i);
		}
	}
	else{
			
		if(get_magic_quotes_gpc()){
			$input=stripslashes($input);
		}
			
		$output=mysql_real_escape_string($input);
	}
	return $output;
}

/*************************************************************************
 *  			Load the core files,
 *************************************************************************/

include	'DAL.php';
include	'MAL.php';
include	'SimpleRelationalRecord.php';
include	'IPolice.php';
include	'ControllerSession.php';
include	'ControllerPost.php';
include	'ControllerGet.php';
include	'ControllerCookie.php';
include	'Controller.php';
include 'Applet.php';


/*----------------------------------------------------------------------*/

/**
 * Get the translation
 */
function _t($key,$args = array()){
	global $zLang;
	
	//if(empty($zLang[strtolower($key)])){
	if(!isset($zLang[$key])){
		return $key;
	}else{
		return vsprintf($zLang[$key] , $args);
	}
}

/**
 * Sets/Gets a session key
 */
function zSession($key){
	if(func_num_args() > 1){// want to set
		$_SESSION[ZONE_PREFIX.$key] = func_get_arg(1);
	}else{
		$ret = $_SESSION[ZONE_PREFIX.$key];
		if(empty($ret))return '';
		return $ret;
	}
}

/**
 * 
 * This function returns the include path of a applet/zone view;
 * How the engine searches for a view:
 * Let an applet view is requested,
 * 		current theme: cooltheme
 * 		current locale: de
 * 		applet name: stat
 * 
 * first try:
 * 
 *  /themes/cooltheme/applets/stat/view_de.php
 *  
 * if above not present next:
 * /themes/cooltheme/applets/stat/view.php
 * 
 *  if above not present next:
 * /applets/stat/view_de.php
 * 
 *  if above not present next:
 * /applets/stat/view.php
 * 
 * if not found at all, return false;
 * 
 * @params $view The view file name
 * @params $type The type name, can be either 'applets' or 'zones'
 * @params $appName The name of the applet or the css.
 * 
 */
function zGetViewPath($appName, $view,$type,$theme='', $locale=''){
	
	if(!in_array($type,array('root','zones','applets'))){
		zDie('Invalid parameter to call zGetViewPath.<br>You called ' . $type.'<br>Only "zones" and "applets" are valid');
	}
	
	global $zShouldCacheURL;
	global $zVarCache;
	global $zAppBaseDir;
	global $zCurrentTheme;
	global $zCurrentLocale;
	
	
		
	
	if(empty($theme)){
		$theme = $zCurrentTheme;
	}
	if(empty($locale)){
		$locale = $zCurrentLocale;
	}
	
	$base = "/";
	
	// All the views of zones are kept inside a view folder. Applet should also follow this?
	if($type=='zones'){
		$view = 'views/'.$view;
		$base = zZoneDir($appName);
	}else{
		$base = zAppletDir($appName);
	}
	
	
	if( $zShouldCacheURL === true && array_key_exists('_pzview_'.$appName.'-'.$view.'-'.$type.'-'.$theme.'-'.$locale, $zVarCache) ){
		return $zVarCache['_pzview_'.$appName.'-'.$view.'-'.$type.'-'.$theme.'-'.$locale];
	}
	

	$path = false;
	
	// /zones/MyZone/themes/cooltheme/views/home_en.php
	if(file_exists( $base . '/themes/'.$theme.'/'.$view.'_'.$locale.'.php' )){
		$path = $base . '/themes/'.$theme.'/'.$view.'_'.$locale.'.php';
	}
	// /zones/MyZone/themes/cooltheme/views/home.php
	else if(file_exists($base . '/themes/'.$theme.'/'.$view.'.php' )){
		$path = $base . '/themes/'.$theme.'/'.$view.'.php';
	}
	else{
	
		// Still no luck?! Try the root theme directories
		
			$base = $zAppBaseDir . '/themes/' . $theme.'/' . $type . '/' .$appName . '/' ;
			
			// /themes/cooltheme/zones/MyZone/css/style_en.css
			 if(file_exists($zAppBaseDir . $base . $view.'_'.$locale.'.php' )){
				$path = $base . $view.'_'.$locale.'.view';
			}
			// /themes/cooltheme/zones/MyZone/css/style.css
			else if(file_exists($zAppBaseDir . $base.$view.'.php' )){
				$path = $base.$view.'.php';
			}
		
	}
	
	if($path==false){
		if($type=='zones'){
			$base = zZoneDir($appName);
		}else{
			$base = zAppletDir($appName);
		}
		// /zones/MyZone/views/home_en.php
		if(file_exists($base . '/'.$view.'_'.$locale.'.php' )){
			$path = $base . '/'.$view.'_'.$locale.'.php';
		}
		// /zones/MyZone/views/home.php
		else if(file_exists($base . '/'.$view.'.php' )){
			$path = $base . '/'.$view.'.php';
		}
	}
	
	$zVarCache['_pzview_'.$appName.'-'.$view.'-'.$type.'-'.$theme.'-'.$locale] = $path;
	file_put_contents(PZ_APP_CACHE_DIR.'/vars.pz',serialize($zVarCache));
	return $path;
	
}
/**
 * Works as zGetViewPath but it does not prepend the application base dir.
 * so that, it can be used either to include a css file or to link a css file.
 *
 * Note: /css or /theme/currenttheme/css paths can be also included. but i think it is not required
 * since these can be easily determined, so why to add an extra check?
 * what do you think?
 * plz put your comment here: www.phpzones.com or mail to me: mailtoaman@gmail.com
 * zCSS function can be used to link/dump the css.
 * 
 */
//function zGetCSSPath($appName,$css='style',$type='zones',$theme='', $locale=''){
function zGetCSSPath($type,$name,$css='style',$theme='', $locale=''){
	if(!in_array($type,array('root','zones','applets'))){
		zDie('Invalid parameter to call zGetViewPath.<br>You called ' . $type.'<br>Only "zones" and "applets" are valid');
	}
	global $zShouldCacheURL;
	global $zAppBaseDir;
	global $zCurrentTheme;
	global $zCurrentLocale;
	global $zVarCache;
	
	if(empty($theme)){
		$theme = $zCurrentTheme;
	}
	if(empty($locale)){
		$locale = $zCurrentLocale;
	}
	
	$base = "/";
	
	if($type=='zones'){
		$base = '/zones/' . $name . '/';
	}else if( $type == 'applets'){
		$base = '/applets/' . $name . '/';
	}
	
	if( $zShouldCacheURL === true && array_key_exists('_pzcss_'.$type.'-'.$name.'-'.$css.'-'.$theme.'-'.$locale, $zVarCache) ){
		return $zVarCache['_pzcss_'.$type.'-'.$name.'-'.$css.'-'.$theme.'-'.$locale];
	}
	
	
	$path = false;
	
	// /zones/MyZone/themes/cooltheme/css/style_en.css
	if(file_exists($zAppBaseDir . $base . 'themes/'.$theme.'/css/'.$css.'_'.$locale.'.css' )){
		$path = $base.  'themes/'.$theme.'/css/'.$css.'_'.$locale.'.css';
	}
	// /zones/MyZone/themes/cooltheme/css/style.css
	else if(file_exists($zAppBaseDir . $base.  'themes/'.$theme.'/css/'.$css.'.css' )){
		$path = $base. 'themes/'.$theme.'/css/'.$css.'.css';
	}
	else if($type!='root'){ // now check if present in theme directory{
	
		// Still no luck?! Try the root theme directories
		
			$base = '/themes/' . $theme.'/' . $type . '/' .$name . '/css/';
			
			// /themes/cooltheme/zones/MyZone/css/style_en.css
			 if(file_exists($zAppBaseDir . $base . $css.'_'.$locale.'.css' )){
				$path = $base . $css.'_'.$locale.'.css';
			}
			// /themes/cooltheme/zones/MyZone/css/style.css
			else if(file_exists($zAppBaseDir . $base.$css.'.css' )){
				$path = $base.$css.'.css';
			}
	}
	
	if($path == false){
		// now check in root dir again 
		$base = "/";
		if($type=='zones'){
			$base = '/zones/' . $name . '/';
		}else if( $type == 'applets'){
			$base = '/applets/' . $name . '/';
		}
		// /zones/MyZone/css/style_en.css
		if(file_exists($zAppBaseDir . $base . 'css/'.$css.'_'.$locale.'.css' )){
			$path = $base.  'css/'.$css.'_'.$locale.'.css';
		}
		// /zones/MyZone/css/style.css
		else if(file_exists($zAppBaseDir . $base.  'css/'.$css.'.css' )){
			$path = $base.'css/'.$css.'.css';
		}
			
	}
	
	$zVarCache['_pzcss_'.$type.'-'.$name.'-'.$css.'-'.$theme.'-'.$locale] = $path;
	file_put_contents(PZ_APP_CACHE_DIR.'/vars.pz',serialize($zVarCache));
	return $path;
	
}
/**
 * Works as zGetViewPath, should be used for zones to find the layout based on theme
 * 
 * Let a layout requested,
 * 		current theme: cooltheme
 * 		current zone : community
 * 		layout name: forum
 * 
 * first try:
 * 
 *  /zones/community/themes/cooltheme/layouts/forum.php
 *  
 *  then,
 *  /themes/cooltheme/zones/community/layouts/forum.php
 *  
 * if above not present next:
 * /zones/community/layouts/forum.php
 * 
 *  if above not present next:
 *  /themes/cooltheme/layouts/forum.php
 * 
 *  if above not present next:
 *  /layouts/forum.php
 *  
 */
function zGetLayoutPath($layout,$theme=''){
	global $zAppBaseDir;
	global $zCurrentTheme;
	global $zZoneName;
	global $zVarCache;
	global $zShouldCacheURL;
	
	if(empty($theme)){
		$theme = $zCurrentTheme;
	}
	
	$key = '_pzlayout_'.$zZoneName.'_'.$layout.'-'.$theme;
	if( $zShouldCacheURL === true && array_key_exists($key, $zVarCache) ){
		return $zVarCache[$key];
	}
	
	$path = false;
	if(file_exists(zZoneDir($zZoneName) . "/themes/$zCurrentTheme/layouts/$layout.php" )){
		$path = zZoneDir($zZoneName) . "/themes/$zCurrentTheme/layouts/$layout.php" ;
	}else if(file_exists($zAppBaseDir . "/themes/$zCurrentTheme/zones/$zZoneName/layouts/$layout.php" )){
		$path = $zAppBaseDir . "/themes/$zCurrentTheme/zones/$zZoneName/layouts/$layout.php" ;
	}else if(file_exists(zZoneDir($zZoneName) . "/layouts/$layout.php" )){
		$path = zZoneDir($zZoneName) . "/layouts/$layout.php" ;
	}else if(file_exists($zAppBaseDir . "/themes/$zCurrentTheme/layouts/$layout.php" )){
		$path = $zAppBaseDir . "/themes/$zCurrentTheme/layouts/$layout.php";
	}else if(file_exists($zAppBaseDir . "/layouts/$layout.php" )){
		$path = $zAppBaseDir . "/layouts/$layout.php"  ;
	}
	
	$zVarCache[$key] = $path;
	file_put_contents(PZ_APP_CACHE_DIR.'/vars.pz',serialize($zVarCache));
	
	return $path;
}
/**
 * Links a css file based on current theme(if any)
 * @param $css The css file name without extension. Extension will be added
 * @param $link If true it links the css, else it dumps the css content in
 * 				style tags. Dumping reduces one get request so it is recomended.
 * 				Dumping may be also used for facebook type application.
 * @param absolute if set true, it will just add the baseurl infront of the css file;
 * @param $media The media attribute of the style tags
 */

$addedCSSFiles = array();
function zCSS($css='style' 		/* Name of the css file without extension */
				,$link = true,  /* use <link> tag or dump content in <style> tag ? */
				$absolute=true 	/* absolute css path given or need to determine? */
				,$type='root' 	/* default 'root' for root directory, 'zones' for zone css and 'applet' for applet css */
				,$name=''		/* enter the zone or applet name or keep "" for 'root' */
				,$media='all' 	/* The media attribute of the style tag */
				){
	global $zZoneName;
	global $zAppBaseDir;
	global $zAppBaseURL;
	global $zCurrentLocale;
	global $addedCSSFiles;
	global $zShouldCacheURL;
	
	if(substr($css,-4)=='.css'){
		$css = substr($css,0,-4);
	}
	
	if($absolute){
		// check if a localized css is present
		if(file_exists($zAppBaseDir . $css.'_'.$zCurrentLocale.'.css')){
			$path = $css.'_' . $zCurrentLocale . '.css';		
		}else{
			$path = $css . '.css';
		}
	}else{
		$path = zGetCSSPath($type,$name,$css);
	}
	
	if($path==false) return;//File not found
	
	if($link ==true){ // Link the css files instead of dumping content
		
		if(!in_array($path,(array)$addedCSSFiles)){//if not added already
			
			$addedCSSFiles[]=$path;
			//link the theme css for the zone
			print("\n\t");
			echo '<link href="'.$zAppBaseURL.$path.'" rel="stylesheet" type="text/css" />';
			print("\n\r");
		}
		
	}else{
		if(!in_array($path,(array)$addedCSSFiles)){//if not added already
			$addedCSSFiles[]=$path;
			print("\n\t<style type='text/css' media='$media'>\n\t\t");
			echo file_get_contents($zAppBaseDir.$path);
			print("\n\t</style>\n\r");
		}
	}
}


// get/set current theme
function zCurrentTheme(){
	if(func_num_args() > 0){// want to set
		zSession('current_theme',func_get_arg(0));
	}else{
		return zSession('current_theme');
	}
}

// get/set current locale
function zCurrentLocale(){
	if(func_num_args() > 0){// want to set
		$locale = func_get_arg(0);
		zSession('current_locale',$locale);
	}else{
		return zSession('current_locale');
	}
}


function zLocales(){
	return zConfig("locales/locale");
}

function zDefaultLocale(){
	if(zConfig('settings/default_locale')){
		return zConfig('settings/default_locale');
	}else{
		return DEFAULT_LOCALE;
	}
}

function __autoload($class_name) {
	global $zClassPaths;
	foreach($zClassPaths as $prefix){
		$path = $prefix . '/' . $class_name . '.php';
		if(file_exists($path)){
			include $path;
			break;
		}
	}
	
	// If class is not found,show a system error
	if(!class_exists($class_name,false)){
		if(!interface_exists($class_name,false)){
			zDie('Class not found : ' . $class_name);
		}
	}
}

/**
 * This function is used by the engine to report system error.
 */

function zDie($zErrMsg, $zErrorDetails=array()){
	if(zConfig('settings/error_page')){
		zRedirect(zURL(zConfig('settings/error_page')) . '?error='.$zErrMsg,false);
	}else{
		include('error.php');
		die();
	}
}
/**
 * @param $url the url
 * @param $addPrefix Pass it false if redirecting to external URL
 */
function zRedirect($url,$addPrefix = true, $addExtension=true){
	global $zAppBaseURL;
	if(empty($url))
		$url = 'index';
	
	
	if($addPrefix){
		header('Location:'.zURL($url,$addExtension));
	}else{
		header('Location:'.$url);
	}
}
function zRefresh($url,$time='2'){
	header("Refresh:$time;url=".zURL($url));
}

function zURL($url,$addExtension = true,$ext=DEFAULT_EXTENSION){
	global $zAppBaseURL;
	if($url[0]=='/')
		$url = substr($url,1);
	$locale = zSession('current_locale')==zSession('default_locale')? '' : zSession('current_locale') . '/';
	
	if($addExtension){
		return $zAppBaseURL.'/'.$locale . $url.$ext;
	}else{
		return $zAppBaseURL.'/' . $url;
	}
}

function zLink($url,$text='', $title='',$class=''){
	if(strpos($url,'://') <2 || strpos($url,'://') >5){
		$url = zURL($url);
	}
	if(empty($text))$text = $url;
	if(empty($title))$title = 'Go to ' . $url;
		
	echo '<a href="'.$url.'" title="'.$title.'" class="'.$class.'">'.$text.'</a>';
}
function zURLPlus($url,$addExtension = true,$ext=DEFAULT_EXTENSION){
	global $zCurrentPath;
	return zURL($zCurrentPath . '/'.$url);
}

function zPath($file){
	global $zAppBaseDir;
	return $zAppBaseDir . '/' . $file;
}
function zBaseURL(){
	global $zAppBaseURL;
	return $zAppBaseURL;
}
function zBaseDir(){
	global $zAppBaseDir;
	return $zAppBaseDir;;
}

/**
 * Link a js file
 *
 * @param $filename JS filename without extension
 * @param $dumpContent if true, without linking dubmp the content in a script tag block.
 * 						might be used in FB
 */


$zAddedJSFiles = array();
function zJS($filename,$link = true,$addBaseUrl=true){
	global $zZoneName;
	global $zAppBaseDir;
	global $zAppBaseURL;
	global $zAddedJSFiles;
	
	if($addBaseUrl===true){
		$full_url = $zAppBaseURL . $filename;
	}else{
		$full_url = $filename;
	}
	if(!in_array($full_url,(array)$zAddedJSFiles)){
		
		$zAddedJSFiles[] = $full_url;
		if($link){
			print ("\n\t<script type='text/javascript'  src='$full_url'></script>\n\r");
			return;
		}else{
			print("\n\t<script type='text/javascript' >\n\t\t");
			echo file_get_contents($zAppBaseDir.$filename);
			print("\n\t</script>\n\r");
		}
	}
}
function zIsPosted(){
	return ($_SERVER['REQUEST_METHOD'] == 'POST');
}


/**
 * Get the Police defined for this path;
 * <police path="sitehome/feedback/save">FormPostPolice</police>
 * 
 * FormPostPolice will be called if one want to call/visit:
 * 
 * 	http://server/sitehome/feedback/save
 * 
 * <police path="sitehome/feedback" subdir = "yes">AnotherPolice</police>
 * 
 * Now, since subdir  is set to "yes", AnotherPolice will be called for any subdirectory including
 * sitehome/feedback.
 * 
 *  so, now both AnotherPolice and FormPostPolice will be called for:
 *  		 	http://server/sitehome/feedback/save
 *  
 * @param $path
 */
function zGetPolices($path){
	global $zConfig;
	$polices = array();
	$max=0;
	$cPolices = $zConfig->xpath("//config/polices/police[@path='$path']");
	
	if($cPolices){
		
		if(is_array($cPolices) && count($cPolices)>1){
			
			foreach($cPolices as $police){
				$polices[]= (string)$police;
			}
		}else{
			
			if($cPolices[0]->attributes()->nopolice=='yes'){
				//var_dump($cPolices);
				return array();
			}
			$polices[] = (string)$cPolices[0];
		}
		
	}
	
	
	// Check if any parent defined a police with subdir="yes"	
	do{
		$cPolices = $zConfig->xpath("//config/polices/police[@path='$path']");
		
		if($cPolices){
			
			if(is_array($cPolices)){
				foreach($cPolices as $police){
					if($police->attributes()->subdir=='yes'){
						$polices[]= (string)$police;
					}
				}
			}else{
				if($cPolices->attributes()->subdir=='yes'){
					$polices[] = (string)$cPolices;
				}
			}
			
		}
		
		
		$path = substr($path,0,strrpos($path,'/'));

	}while(strlen($path)>0);
		
	
	$polices = array_unique($polices);	
	return $polices;
}

function zTotalTime(){
	global $zTimeStart;
	$zTimeEnd = microtime( true );
	return $zTimeEnd - $zTimeStart;
}
function zTimeTaken(){
	global $zPageTimeStart;
	$zTimeEnd = microtime( true );
	return $zTimeEnd - $zPageTimeStart;
}
function zCurrentUrl(){
	global $zAppDocBase;
	return substr( $_SERVER["REQUEST_URI"],strlen( $zAppDocBase ) );
	//return ];
}

/**
 * Returns the current URL parts in array. 
 * 
 * For example, current URL is now: http://www.xyz.com/products/categories/vehicles/cars.html
 * zURLParts() will rturn an array like this: array("products","categories","vehicles","cars");
 * 
 * If a parameter is passed, such as: zURLParts(1);
 * If a second paramter is passed, it will skip the locale parts;
 * it will return "categories" in case above example.
 * 
 */
function zURLParts(){
	global $zURLParts;
	
	//return if there is no url parts
	if(empty($zURLParts))return false;
	
	
	$args = func_get_args();
	$numArg  = count($args);
	//var_dump($args);
	
	switch($numArg){
		case 0:{
			return $zURLParts;
		}
		case 1:{
			if(is_int($args[0])){
				if(count($zURLParts) > $args[0]){
					return $zURLParts[$args[0]];
				}
			}else{
				
				if($args[0] == 'last'){
					return end($zURLParts);
				}
			}
			break;
		}
		case 2:{ // skip locale
			if(is_int($args[0])){
				if(in_array($zURLParts[0], zConfig('locales/locale'))){
						array_shift($zURLParts); 
				}
				if(count($zURLParts) > $args[0]){
					return $zURLParts[$args[0]];
				}
			}
			break;
		}
	}
}

/**
 * Use an applet
 * 
 * @param $name Name of the applet
 * @param $method Name of the method to call
 * @param $params optional parameter as array
 */
function zApplet($name,$method='',$params = array()){	
	zInclude(zAppletDir($name) . '/app_'.$name . '.php',"'$name' Applet controller not defined");
	
	// include the lang file
	global $zCurrentLocale;
	global $zDefaultLocale;
	zInclude(zAppletDir($name) . '/lang/'.$zDefaultLocale . '.php');
	zInclude(zAppletDir($name) . '/lang/'.$zCurrentLocale . '.php');
	
	$className = 'app_'.$name;
	if(!class_exists($className)){
		zDie("'$className' class not defined");
	}
	$appletObj = new $className($name);
	
	if(empty($method)){// hmm... you want the object
		return $appletObj;
	}
	
	// call the method
	call_user_func_array(array($appletObj, $method),$params);
}
/**
 * Show a view file of an applet
 * 
 * @param $name Name of the applet
 * @param $view Name of the view file without extension
 * @param $params Optional parameters as HASH array
 * 
 */
function zAppletView($name,$view='view',$params = array(),$includeClass = true){
	// Though we will not instanciate, there might be some static method
	if($includeClass == true){
		zInclude(zAppletDir($name) . '/app_'.$name . '.php');
	}
	
	// include the lang file
	global $zCurrentLocale;
	global $zDefaultLocale;
	zInclude(zAppletDir($name) . '/lang/'.$zDefaultLocale . '.php');
	zInclude(zAppletDir($name) . '/lang/'.$zCurrentLocale . '.php');
	
	
	zInclude(zAppletDir($name) .'/'.$view . '.php',"view '$view.php' not found in applet '$name'",$params);
}

/**
 * You can put your applets even outside your application root directory.
 * In such case, put an entry into the conf.php file in this way:
 * 
 * $app_conf['applet_dir']['AnAppletName'] = "../repo/Applets/";
 * 
 * @param $applet The name of the applet.
 */
function zAppletDir($applet){
	$dir = zConfig("applets/applet[@name='$applet']/location");
	
	if(!$dir){// find out where it is
		global $zAppBaseDir;
		global $zZoneName;
		
		// Check if the current zone has its own applet
		if(is_dir($zAppBaseDir . '/zones/' . $zZoneName.'/applets/' . $applet)){
		 	$dir = $zAppBaseDir .'/zones/' . $zZoneName. '/applets/' . $applet;
		}else{// Try to get from /applets directory
			$dir = $zAppBaseDir . '/applets/' . $applet;
		}
	}
	
	// finally check if there is any applet folder really exists
	if(!is_dir($dir)){
		zDie("Applet directory not found: " . $applet);
	}
	
	return $dir;
}

/**
 * You can put your zones even outside your application root directory.
 * In such case, put an entry into the conf.php file in this way:
 * 
 * $app_conf['zone_dir']['AnAppletName'] = "/usr/opt/repo/Zones/";
 * 
 * @param $applet The name of the applet.
 * @return unknown_type
 */
function zZoneDir($zone){
	if(zConfig("zones/zone[@name='$zone']/location")){
		return str_replace("%PZ_FRAMEWORK_DIRECTORY%", PZ_FRAMEWORK_DIRECTORY, zConfig("zones/zone[@name='$zone']/location"));
	}else{
		global $zAppBaseDir;
		return $zAppBaseDir . '/zones/' . $zone;
	}
}
/**
 * This function return the actual url of a zone.
 *  
 * For example, if the current zone is AdminZone, this function will return
 * 		http://yourserver/zones/AdminZone
 * 
 * It can also be used get the accessable location of resource,like:
 * 
 * 	<img src="<?= zZoneURL('img/myimge.png',true)?> />"
 * 
 * 
 * @param $path if nothing is passed, it will pass the zone url, else it will
 * 			return the accessable url of the path;
 * @param $actual_url if passed true, it will return the actual url as shown above.
 * 
 */
function zZoneURL($path=false,$actual_url=false){
	global $zZoneName;
	global $zAppBaseURL;
	if($path != false){
		return $zAppBaseURL . ($actual_url==true?'/zones/':'/') . $zZoneName . '/' . $path;
	}else{
		return $zAppBaseURL . '/zones/' . $zZoneName;
	}
}
function zCurrentZone(){
	global $zZoneName;
	return $zZoneName;
}

function zPost($key, $sanitize = false){
	return zSafe($_POST[$key],$sanitize);
	
}

function zGet($key, $sanitize = false){
	return zSafe($_GET[$key],$sanitize);
}

/**
 * Cleans a value by sanitizing and stripping tags 
 */
function zSafe( $val, $sanitize=false ){
	
	if($sanitize){
		switch ($sanitize){
			case 'email':
				if(!filter_var($val, FILTER_VALIDATE_EMAIL)){
					$val = false;
				}
				break;
			
			case 'plain': // no tag, no esp char
				
				$val  = filter_var($val, FILTER_SANITIZE_STRIPPED | FILTER_SANITIZE_SPECIAL_CHARS);
				
				break;
				
			case 'int':
				if(!filter_var($val, FILTER_VALIDATE_INT)){
					$val = false;
				}
				
				break;
			
			case 'url':
				if(!filter_var($val, FILTER_VALIDATE_URL)){
					$val = false;
				}
				$val = filter_var($val, FILTER_SANITIZE_URL);	
				break;
				
			case 'mysql':
				$mal = new MAL();
				//$val= mysql_real_escape_string($val);
				$val = $mal->clean($val);
				break;
		}
	}

	return $val;
}

/**
 * Creates a url compatible string.
 * 
 * For example, title of a blog post is "Hello world how's life?"
 * You may want this as: "hello-world-hows-life".
 * 
 * This function does that :)
 * 
 * @param unknown_type $text
 */
function zSEOUrl($text){
	$text=strtolower($text); 
$code_entities_match = array(' ','--','&quot;','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','*','+','~','`','='); 
$code_entities_replace = array('-','-','','','','','','','','','','','','','','','','','','','','','','','',''); 
$text = str_replace($code_entities_match, $code_entities_replace, $text); 
return $text;
}
/**
 * Stores a variable in session. Removes the value from session on first use
 * 
 * If two parameter is passed, it sets the value, if one passed it removes the key and return the value;
 *
 * @param $key
 */
function zFlash($key){
	if(func_num_args() > 1){// want to set
		$_SESSION[ZONE_PREFIX.$key] = func_get_arg(1);
	}else{
		$ret = $_SESSION[ZONE_PREFIX.$key];
		unset($_SESSION[ZONE_PREFIX.$key]);
		return $ret;
	}
}

/**
 * This function includes the current view file into the caller.
 * 
 * Usually this function is used in the layout files to show the view.
 */

$zCurrentView = '';
$zCurrentViewParams = array();
$zCurrentLayoutParams = array();
function zShowCurrentView(){
	global $zZoneName;
	global $zCurrentView;
	global $zCurrentViewParams;
	global $zCurrentLayoutParams;
	$viewFile = zGetViewPath($zZoneName,$zCurrentView,'zones');
	if($viewFile == false)zDie("View file not found");
	extract($zCurrentLayoutParams);
	extract($zCurrentViewParams);
	
	include($viewFile);
}

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
 function recursiveDelete($str){
	 if(is_file($str)){
		return @unlink($str);
	 }
	elseif(is_dir($str)){
		$scan = glob(rtrim($str,'/').'/*');
		foreach($scan as $index=>$path){
			recursiveDelete($path);
		}
		return @rmdir($str);
	}
 }
?>